<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>指标监控 - RustCloud 仪表板</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background-color: #f5f5f5;
            color: #333;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px 0;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
        }

        .header h1 {
            font-size: 28px;
            font-weight: 600;
        }

        .nav {
            background: white;
            padding: 15px 0;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            margin-bottom: 30px;
        }

        .nav ul {
            list-style: none;
            display: flex;
            gap: 30px;
        }

        .nav a {
            text-decoration: none;
            color: #333;
            font-weight: 500;
            padding: 10px 15px;
            border-radius: 5px;
            transition: background-color 0.3s;
        }

        .nav a:hover, .nav a.active {
            background-color: #667eea;
            color: white;
        }

        .search-bar {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }

        .search-input {
            width: 100%;
            padding: 12px 16px;
            border: 2px solid #e1e5e9;
            border-radius: 8px;
            font-size: 16px;
            transition: border-color 0.3s;
        }

        .search-input:focus {
            outline: none;
            border-color: #667eea;
        }

        .metrics-grid {
            display: grid;
            grid-template-columns: 1fr 2fr;
            gap: 20px;
        }

        .metrics-list {
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        .metrics-list h3 {
            background: #f8f9fa;
            padding: 15px 20px;
            margin: 0;
            border-bottom: 1px solid #e1e5e9;
        }

        .metric-item {
            padding: 15px 20px;
            border-bottom: 1px solid #f1f3f4;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .metric-item:hover {
            background-color: #f8f9fa;
        }

        .metric-item.active {
            background-color: #667eea;
            color: white;
        }

        .metric-name {
            font-weight: 600;
            margin-bottom: 5px;
        }

        .metric-help {
            font-size: 14px;
            color: #666;
            margin-bottom: 8px;
        }

        .metric-item.active .metric-help {
            color: #e1e5e9;
        }

        .metric-type {
            display: inline-block;
            padding: 2px 8px;
            background-color: #e1e5e9;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 500;
        }

        .metric-item.active .metric-type {
            background-color: rgba(255,255,255,0.2);
            color: white;
        }

        .metric-details {
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            padding: 20px;
        }

        .metric-values {
            max-height: 400px;
            overflow-y: auto;
            margin-top: 15px;
        }

        .value-item {
            background: #f8f9fa;
            border-radius: 5px;
            padding: 10px;
            margin-bottom: 10px;
        }

        .value-number {
            font-size: 24px;
            font-weight: bold;
            color: #667eea;
        }

        .value-labels {
            margin-top: 5px;
            font-size: 12px;
        }

        .label-tag {
            display: inline-block;
            background: #e1e5e9;
            padding: 2px 6px;
            border-radius: 3px;
            margin: 2px;
            font-family: monospace;
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: #666;
        }

        .no-results {
            text-align: center;
            padding: 40px;
            color: #666;
        }

        .refresh-button {
            background: #667eea;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            margin-bottom: 20px;
            transition: background-color 0.3s;
        }

        .refresh-button:hover {
            background: #5a67d8;
        }

        .error-message {
            background: #fef2f2;
            border: 1px solid #fecaca;
            color: #dc2626;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <header class="header">
        <div class="container">
            <h1>📊 指标监控</h1>
        </div>
    </header>

    <nav class="nav">
        <div class="container">
            <ul>
                <li><a href="/">概览</a></li>
                <li><a href="/metrics" class="active">指标</a></li>
                <li><a href="/alerts">告警</a></li>
                <li><a href="/apm">APM</a></li>
                <li><a href="/health">健康检查</a></li>
            </ul>
        </div>
    </nav>

    <main class="container">
        <div class="search-bar">
            <input type="text" class="search-input" id="search-input" placeholder="搜索指标名称...">
        </div>

        <button class="refresh-button" onclick="loadMetrics()">🔄 刷新指标</button>

        <div id="error-container"></div>

        <div class="metrics-grid">
            <div class="metrics-list">
                <h3>指标列表</h3>
                <div id="metrics-container">
                    <div class="loading">正在加载指标...</div>
                </div>
            </div>

            <div class="metric-details">
                <h3 id="detail-title">选择一个指标查看详情</h3>
                <div id="detail-content">
                    <div class="no-results">
                        👈 从左侧列表中选择一个指标以查看其详细信息和当前值
                    </div>
                </div>
            </div>
        </div>
    </main>

    <script>
        let allMetrics = [];
        let currentMetric = null;

        // 加载指标数据
        async function loadMetrics() {
            try {
                showLoading();
                const response = await fetch('/api/metrics');
                const result = await response.json();
                
                if (result.success) {
                    allMetrics = result.data;
                    displayMetrics(allMetrics);
                    hideError();
                } else {
                    showError('获取指标失败: ' + result.error);
                }
            } catch (error) {
                console.error('加载指标失败:', error);
                showError('无法连接到服务器');
            }
        }

        // 显示指标列表
        function displayMetrics(metrics) {
            const container = document.getElementById('metrics-container');
            
            if (metrics.length === 0) {
                container.innerHTML = '<div class="no-results">没有找到指标</div>';
                return;
            }

            container.innerHTML = metrics.map(metric => `
                <div class="metric-item" onclick="selectMetric('${metric.name}')">
                    <div class="metric-name">${metric.name}</div>
                    <div class="metric-help">${metric.help || '无描述'}</div>
                    <span class="metric-type">${metric.metric_type}</span>
                </div>
            `).join('');
        }

        // 选择指标
        function selectMetric(metricName) {
            // 更新选中状态
            document.querySelectorAll('.metric-item').forEach(item => {
                item.classList.remove('active');
            });
            event.currentTarget.classList.add('active');

            // 查找指标数据
            currentMetric = allMetrics.find(m => m.name === metricName);
            if (currentMetric) {
                displayMetricDetails(currentMetric);
            }
        }

        // 显示指标详情
        function displayMetricDetails(metric) {
            document.getElementById('detail-title').textContent = metric.name;
            
            const content = document.getElementById('detail-content');
            
            if (metric.metrics.length === 0) {
                content.innerHTML = '<div class="no-results">该指标暂无数据</div>';
                return;
            }

            content.innerHTML = `
                <div><strong>类型:</strong> ${metric.metric_type}</div>
                <div><strong>描述:</strong> ${metric.help || '无描述'}</div>
                <div><strong>指标数量:</strong> ${metric.metrics.length}</div>
                <div class="metric-values">
                    ${metric.metrics.map(m => {
                        const value = formatMetricValue(m.value);
                        const labels = Object.entries(m.labels).map(([k, v]) => 
                            `<span class="label-tag">${k}="${v}"</span>`
                        ).join('');
                        const timestamp = new Date(m.timestamp).toLocaleString();
                        
                        return `
                            <div class="value-item">
                                <div class="value-number">${value}</div>
                                <div class="value-labels">${labels || '<span class="label-tag">无标签</span>'}</div>
                                <div style="font-size: 11px; color: #999; margin-top: 5px;">更新时间: ${timestamp}</div>
                            </div>
                        `;
                    }).join('')}
                </div>
            `;
        }

        // 格式化指标值
        function formatMetricValue(value) {
            if (typeof value === 'object') {
                if (value.Counter !== undefined) {
                    return value.Counter.toFixed(2);
                } else if (value.Gauge !== undefined) {
                    return value.Gauge.toFixed(2);
                } else if (value.Histogram !== undefined) {
                    return `总数: ${value.Histogram.count}, 总和: ${value.Histogram.sum.toFixed(2)}`;
                } else if (value.Summary !== undefined) {
                    return `总数: ${value.Summary.count}, 总和: ${value.Summary.sum.toFixed(2)}`;
                }
            }
            return String(value);
        }

        // 搜索功能
        function setupSearch() {
            const searchInput = document.getElementById('search-input');
            searchInput.addEventListener('input', (e) => {
                const searchTerm = e.target.value.toLowerCase();
                const filteredMetrics = allMetrics.filter(metric => 
                    metric.name.toLowerCase().includes(searchTerm) ||
                    (metric.help && metric.help.toLowerCase().includes(searchTerm))
                );
                displayMetrics(filteredMetrics);
            });
        }

        // 显示加载状态
        function showLoading() {
            document.getElementById('metrics-container').innerHTML = '<div class="loading">正在加载指标...</div>';
        }

        // 显示错误
        function showError(message) {
            const errorContainer = document.getElementById('error-container');
            errorContainer.innerHTML = `<div class="error-message">❌ ${message}</div>`;
        }

        // 隐藏错误
        function hideError() {
            document.getElementById('error-container').innerHTML = '';
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', () => {
            setupSearch();
            loadMetrics();
            
            // 设置自动刷新（每30秒）
            setInterval(loadMetrics, 30000);
        });
    </script>
</body>
</html>